<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="单据编号" prop="documentNumber">
        <el-input
          v-model="queryParams.documentNumber"
          placeholder="请输入单据编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="单据日期" prop="documentDate">
        <el-date-picker
          v-model="queryParams.documentDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <!--      类型（1-项目，3办公室，2零星，4销售，5采购）-->
      <el-form-item label="类型" prop="type">
        <el-select
          v-model="queryParams.type"
          placeholder="请选择类型"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.ERP_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="归属项目" prop="belongingProject">
        <el-select
          v-model="queryParamsPoject.type"
          placeholder="请选择归属项目"
          clearable
          filterable
          remote
          :remote-method="fetchProjects"
          :loading="loading"
          class="!w-240px"
          @change="handleSelectChange"
        >
          <el-option
            v-for="project in projects"
            :key="project.id"
            :label="project.projectName"
            :value="project.id"
          />
        </el-select>
        <!--        审核状态（详情查看字典表）-->
      </el-form-item>
      <el-form-item label="审核状态" prop="auditStatus">
        <el-select
          v-model="queryParams.auditStatus"
          placeholder="请选择审核状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CRM_AUDIT_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px"/>
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px"/>
          重置
        </el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['purchase:material-demand:create']"
        >
          <Icon icon="ep:plus" class="mr-5px"/>
          新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['purchase:material-demand:export']"
        >
          <Icon icon="ep:download" class="mr-5px"/>
          导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="单据编号" align="center" prop="documentNumber"/>
      <el-table-column label="商品信息" align="center" prop="goodsInfo"/>
      <el-table-column
        label="单据日期"
        align="center"
        prop="documentDate"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="类型" align="center" prop="type">
        <template #default="scope">
          {{ parseType(scope.row.type) }} <!-- 直接在模板中解析 type -->
        </template>
      </el-table-column>
      <el-table-column label="归属项目" align="center" prop="belongingProject"/>
      <el-table-column align="center" fixed="right" label="审核状态" prop="auditStatus">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.CRM_AUDIT_STATUS" :value="scope.row.auditStatus"/>
        </template>
      </el-table-column>

      <el-table-column label="操作" fixed="right" width="200px" align="center">
        <template #default="scope">
          <el-button

            v-if="scope.row.auditStatus ==='0'"
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['purchase:material-demand:update']"
          >
            编辑
          </el-button>

          <el-button
            v-if="scope.row.auditStatus ==='0'"
            v-hasPermi="['purchase:material-demand:updateById']"
            link
            type="primary"
            @click="handleSubmit(scope.row)"
          >
            提交审核
          </el-button>

          <el-button
            v-else
            v-hasPermi="['purchase:material-demand:update']"
            link
            type="primary"
            @click="handleProcessDetail(scope.row)"
          >
            查看审批
          </el-button>

          <el-button
            v-if="scope.row.auditStatus ==='0'"
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['purchase:material-demand:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <MaterialDemandForm
ref="formRef" :typeP="typeP" :documentNumberDateA="documentNumberDateA"
                      :documentNumber="documentNumber" @success="getList"/>
</template>

<script setup lang="ts">
import {dateFormatter} from '@/utils/formatTime'
import download from '@/utils/download'
import {MaterialDemandApi, MaterialDemandVO} from '@/api/werp/purchase/materialdemand'
import MaterialDemandForm from './MaterialDemandForm.vue'
import {DICT_TYPE, getIntDictOptions} from "@/utils/dict";
import {PojectInfoApi} from "@/api/material/pojectinfo";
import {useRouter} from 'vue-router'
import {DocumentSerialApi, DocumentSerialVO} from "@/api/werp/purchase/documentserial";


// import * as MaterialDemandApi from '@/api/crm/receivable'

/** 单据 列表 */
defineOptions({name: 'MaterialDemand'})

const message = useMessage() // 消息弹窗
const {t} = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<MaterialDemandVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  documentNumber: undefined,
  documentDate: [null, null],
  type: undefined,
  belongingProject: undefined,
  auditStatus: undefined,
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {

  loading.value = true
  try {
    const data = await MaterialDemandApi.getMaterialDemandPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}
const serialNumberFormData = ref({
  id: undefined,
  documentNumber: undefined,
  initial: undefined,
  djDate: undefined,
  serialNumber: undefined,
})
/** 添加/修改操作 */
const formRef = ref()
const typeP = ref('')
const documentNumberDateA = ref('')
const documentNumber = ref()

const openForm = async (type: string, id?: number) => {

  if (type === 'create') {
    documentNumberDateA.value = new Date().toString();
   
    const data = serialNumberFormData.value as unknown as DocumentSerialVO
    data.initial = "XMSQ"
    const djNumber = await DocumentSerialApi.createDocumentSerial(data)
    documentNumber.value = djNumber as any
  } else {
    documentNumberDateA.value = '';
    documentNumber.value = null;
  }
  typeP.value = type
  formRef.value.open(type, id)

}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await MaterialDemandApi.deleteMaterialDemand(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {
  }
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await MaterialDemandApi.exportMaterialDemand(queryParams)
    download.excel(data, '单据.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 提交审核 **/
const handleSubmit = async (row: MaterialDemandVO) => {
  console.log('提交审核:', row)
  await message.confirm(`您确定提交编号为【${row.documentNumber}】的回款审核吗？`)
  await MaterialDemandApi.submitReceivable(row.id);
  message.success('提交审核成功！')
  await getList()
}


interface Project {
  id: number;
  projectName: string;
}

const queryParamsPoject = ref({
  type: '',
  pageNo: 1,
  pageSize: 10,
  projectName: "",
  phone: undefined,
  createTime: [],
  head: undefined,
});

const projects = ref<Project[]>([]);

const fetchProjects = async () => {
  loading.value = true;
  try {
    const response = await PojectInfoApi.getPojectInfoPage(queryParamsPoject);
    console.log('Projects:', response)
    projects.value = response.list.map(project => ({
      id: project.id,
      projectName: project.projectName
    }));

  } catch (error) {
    console.error('Failed to fetch projects:', error);
  } finally {
    loading.value = false;
  }
};

const handleSelectChange = (value: number) => {
  console.log('可以的:', value);
  // 进行其他操作
};
const router = useRouter()

const handleProcessDetail = (row: MaterialDemandVO) => {
  console.log("documentNumber78:", row.documentNumber.toString())
  router.push({
    name: 'BpmProcessInstanceDetail',
    query: {id: row.processInstanceId, documentNumber: row.documentNumber.toString()}
  })
}

const parseType = (value) => {
  switch (value) {
    case "1":
      return '项目';
    case "2":
      return '零星';
    case "3":
      return '办公室';
    default:
      return '未知类型';
  }
};


/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
